package com.briup.server;

import com.briup.entity.Environment;
import com.briup.exception.EnvException;
import com.briup.interfaces.Configuration;
import com.briup.interfaces.DbStore;
import com.briup.interfaces.Log;
import com.briup.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;

/**
 * 入库模块实现
 */
public class DbStoreImpl implements DbStore {
    // 定义批处理条数
    private int batchSize;
    private Log log;

    @Override
    public void init(Properties properties) {
        batchSize = Integer.parseInt(properties.getProperty("batch-size"));
    }

    @Override
    public void setConfiguration(Configuration configuration) {
        log = configuration.getLog();
    }

    @Override
    public void dbStore(Collection<Environment> coll) throws EnvException {

        Connection conn = null;
        PreparedStatement ps = null;
        // 定义一个计数器
        int count = 0;
        // 定义一个记录上一天的变量
        int preDay = -1;
        // 准备一个集合用来收录那些天（表）中有数据
        Set<Integer> set = new TreeSet<>();
        try {
            conn = JdbcUtil.getDruidConnection();
            for (Environment environment : coll) {
                // 获得时间
                Timestamp time = environment.getTime();
                // Calendar 日历
                Calendar calendar = Calendar.getInstance();
                // 建立联系
                calendar.setTime(time);
                // 取出天
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                // 每有一个day 就放入集合
                set.add(day);
                // 上一条是28
                // 下一条也是28
                // 如何处理上一天和下一天的关系，最多只产生31个ps对象

                // 判断上一天和当前天的关系
                if (preDay != day) {  // preDay = -1,day = 20
                    if (ps != null) {
                        ps.executeBatch();
                        ps.clearBatch();
                        ps.close();
                    }
                    // 创建预定义的sql
                    String sql = "insert into env_detail_" + day + " values(?,?,?,?,?,?,?,?,?)";
                    ps = conn.prepareStatement(sql);
                    preDay = day;  // preDay = 20
                }
                // 给ps赋值
                ps.setString(1, environment.getName());
                ps.setString(2, environment.getSrcId());
                ps.setString(3, environment.getDesId());
                ps.setString(4, environment.getAddress());
                ps.setInt(5, environment.getCount());
                ps.setString(6, environment.getCmd());
                ps.setInt(7, environment.getStatus());
                ps.setFloat(8, environment.getData());
                ps.setTimestamp(9, environment.getTime());
                // 批处理
                ps.addBatch();
                count++;
                // 假设每5000条提交一次
                if (count % batchSize == 0) {
                    ps.executeBatch();
                    ps.clearBatch();
                }
            }
            // 循环外在提交一次，防止漏掉
            if (ps != null && count % batchSize != 0) {
                ps.executeBatch();
                ps.clearBatch();
                System.out.println("入库成功");
                System.out.println(set);
            }
        } catch (SQLException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(ps, conn);
        }
    }
}

